import requests
import json
import os
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.contrib.auth.models import User
from django.conf import settings 
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.utils import timezone
from apps.credentials.models import Credential, CredentialImportLog

@csrf_exempt
def chat_api(request):
    """处理聊天和文件上传的API"""
    # 如果有文件上传，处理文件解析
    if request.FILES:
        return handle_file_upload(request)
    else:
        return handle_chat_message(request)

def handle_chat_message(request):
    """处理普通聊天消息 - 保持原有逻辑"""
    try:
        data = json.loads(request.body)
        user_message = data.get('message', '')
        
        print(f"收到消息: {user_message}")  # 调试日志
        
        # 检测文件上传关键词，引导用户使用上传功能
        upload_keywords = ['上传', '附件', '文件', '导入', 'upload', 'file']
        if any(keyword in user_message for keyword in upload_keywords):
            return JsonResponse({
                'success': True,
                'response': '请使用页面上方的"📎 上传文件"按钮来上传账号密码文件。支持格式：TXT、Excel、Word、PDF等。上传后系统会自动解析并保存到数据库。'
            })
        
        if not user_message:
            return JsonResponse({'success': False, 'error': '消息不能为空'})
        
        # 从settings获取配置
        api_key = settings.DEEPSEEK_CONFIG['api_key']
        base_url = settings.DEEPSEEK_CONFIG['base_url']
        
        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": "deepseek-chat",
            "messages": [
                {
                    "role": "user", 
                    "content": user_message
                }
            ],
            "stream": False
        }
        
        print(f"发送请求到: {base_url}/chat/completions")  # 调试日志
        
        response = requests.post(
            f"{base_url}/chat/completions",
            headers=headers,
            json=payload,
            timeout=30
        )
        
        print(f"API响应状态码: {response.status_code}")  # 调试日志
        
        if response.status_code == 200:
            result = response.json()
            print(f"API响应内容: {result}")  # 调试日志
            
            ai_response = result['choices'][0]['message']['content']
            
            return JsonResponse({
                'success': True,
                'response': ai_response
            })
        else:
            error_detail = response.text
            print(f"API错误详情: {error_detail}")  # 调试日志
            return JsonResponse({
                'success': False,
                'error': f'API调用失败: {response.status_code} - {error_detail}'
            })
            
    except Exception as e:
        print(f"异常错误: {str(e)}")  # 调试日志
        return JsonResponse({
            'success': False,
            'error': f'请求异常: {str(e)}'
        })

def handle_file_upload(request):
    """处理文件上传和解析 - 新增功能"""
    try:
        uploaded_file = request.FILES.get('file')
        if not uploaded_file:
            return JsonResponse({'success': False, 'error': '没有收到文件'})
        
        print(f"收到文件: {uploaded_file.name}")  # 调试日志
        
        # 检查文件类型
        allowed_types = ['.txt', '.xlsx', '.xls', '.docx', '.pdf', '.csv']
        file_ext = os.path.splitext(uploaded_file.name)[1].lower()
        
        if file_ext not in allowed_types:
            return JsonResponse({
                'success': False, 
                'error': f'不支持的文件类型: {file_ext}，支持的类型: {", ".join(allowed_types)}'
            })
        
        # 读取文件内容
        file_content = parse_file_content(uploaded_file, uploaded_file.name)
        print(f"文件内容长度: {len(file_content)}")  # 调试日志
        
        # 使用DeepSeek解析账号密码
        parse_result = parse_credentials_with_deepseek(file_content, uploaded_file.name)
        print(f"解析结果: {parse_result}")  # 调试日志
        
        # 保存文件到media
        file_path = f'credentials/{timezone.now().strftime("%Y/%m/%d")}/{uploaded_file.name}'
        uploaded_file.seek(0)  # 重置文件指针
        saved_path = default_storage.save(file_path, ContentFile(uploaded_file.read()))
        
        response_data = {
            'success': True,
            'message': '文件解析完成',
            'file_info': {
                'file_name': uploaded_file.name,
                'file_path': saved_path,
                'file_size': uploaded_file.size
            },
            'parse_result': parse_result
        }
        
        # 如果解析出错，在响应中包含错误信息
        if 'error' in parse_result:
            response_data['warning'] = parse_result['error']
        
        return JsonResponse(response_data)
        
    except Exception as e:
        print(f"文件处理异常: {str(e)}")  # 调试日志
        return JsonResponse({'success': False, 'error': f'文件处理失败: {str(e)}'})

def parse_file_content(file, filename):
    """根据文件类型读取内容"""
    file_ext = filename.split('.')[-1].lower()
    
    try:
        if file_ext == 'txt':
            content = file.read().decode('utf-8')
        elif file_ext in ['xlsx', 'xls']:
            import pandas as pd
            df = pd.read_excel(file)
            content = df.to_string()
        elif file_ext == 'docx':
            from docx import Document
            doc = Document(file)
            content = '\n'.join([para.text for para in doc.paragraphs])
        elif file_ext == 'pdf':
            import pdfplumber
            content = ''
            with pdfplumber.open(file) as pdf:
                for page in pdf.pages:
                    content += page.extract_text() or '' + '\n'
        elif file_ext == 'csv':
            import pandas as pd
            df = pd.read_csv(file)
            content = df.to_string()
        else:
            # 默认按文本处理
            content = file.read().decode('utf-8', errors='ignore')
        
        return content
    except Exception as e:
        raise Exception(f"文件读取失败: {str(e)}")

def parse_credentials_with_deepseek(file_content, filename):
    """使用DeepSeek解析账号密码文件"""
    try:
        # 从settings获取配置
        api_key = settings.DEEPSEEK_CONFIG['api_key']
        base_url = settings.DEEPSEEK_CONFIG['base_url']
        
        prompt = f"""
请解析以下账号密码数据，返回严格的JSON格式。数据格式包含：序号、位置、设备名称、用户名、密码、URL、状态、备注等信息。

解析要求：
1. 提取每条记录的完整信息
2. 识别状态：系统正常、网址打不开、基本废弃、警告等
3. 标准化URL格式（确保是完整的URL）
4. 识别协议类型：HTTPS、HTTP、SSH、Telnet等
5. 返回格式必须严格遵循：
{{
    "credentials": [
        {{
            "location": "位置",
            "device_name": "设备名称", 
            "username": "用户名",
            "password": "密码", 
            "url": "访问地址",
            "protocol": "协议类型",
            "status": "状态",
            "notes": "备注"
        }}
    ],
    "total_count": 总数,
    "success_count": 成功解析数,
    "file_name": "{filename}"
}}

数据内容：
{file_content}

注意：只返回JSON格式，不要其他文字说明。
"""
        
        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": "deepseek-chat",
            "messages": [
                {
                    "role": "user", 
                    "content": prompt
                }
            ],
            "stream": False
        }
        
        print(f"发送解析请求到DeepSeek API")  # 调试日志
        
        response = requests.post(
            f"{base_url}/chat/completions",
            headers=headers,
            json=payload,
            timeout=60  # 文件解析可能需要更长时间
        )
        
        print(f"解析API响应状态码: {response.status_code}")  # 调试日志
        
        if response.status_code == 200:
            result = response.json()
            ai_response = result['choices'][0]['message']['content']
            print(f"解析API响应内容: {ai_response}")  # 调试日志
            
            return extract_json_from_response(ai_response)
        else:
            error_detail = response.text
            print(f"解析API错误详情: {error_detail}")  # 调试日志
            return {"error": f"API调用失败: {response.status_code}", "credentials": []}
            
    except Exception as e:
        print(f"解析过程异常: {str(e)}")  # 调试日志
        return {"error": f"解析失败: {str(e)}", "credentials": []}

def extract_json_from_response(content):
    """从DeepSeek响应中提取JSON数据"""
    import re
    
    try:
        # 清理响应内容
        content = content.strip()
        
        # 移除可能的代码块标记
        if content.startswith('```json'):
            content = content[7:]
        elif content.startswith('```'):
            content = content[3:]
        
        if content.endswith('```'):
            content = content[:-3]
        
        # 提取JSON部分
        json_match = re.search(r'\{.*\}', content, re.DOTALL)
        if json_match:
            json_str = json_match.group()
            result = json.loads(json_str)
            
            # 验证必要字段
            if 'credentials' in result:
                print(f"成功提取JSON数据，共 {len(result['credentials'])} 条记录")  # 调试日志
                return result
            else:
                print("解析结果缺少credentials字段")  # 调试日志
                return {"error": "解析结果格式不正确", "credentials": []}
        else:
            print("未找到有效的JSON数据")  # 调试日志
            return {"error": "未找到有效的JSON数据", "credentials": []}
            
    except json.JSONDecodeError as e:
        print(f"JSON解析失败: {str(e)}")  # 调试日志
        return {"error": f"JSON解析失败: {str(e)}", "credentials": []}
    except Exception as e:
        print(f"提取JSON异常: {str(e)}")  # 调试日志
        return {"error": f"提取过程出错: {str(e)}", "credentials": []}